package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.dto.course.CourseDTO;
import com.qk.entity.Course;
import com.qk.management.mapper.CourseMapper;
import com.qk.management.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author: ZgYn
 * @Date 2025/10/8 19:49
 * @name：CourseServiceImpl
 */
@Service
public class CourseServiceImpl implements CourseService {

    @Autowired
    private CourseMapper courseMapper;
    @Override
    public PageResult<Course> getCourses(CourseDTO courseDTO) {
        PageHelper.startPage(courseDTO.getPage(), courseDTO.getPageSize());
        List<Course> courses = courseMapper.selectByExample(courseDTO);
        Page<Course> pageInfo = (Page<Course>) courses;
        return PageResult.<Course>builder()
                .total((int) pageInfo.getTotal())
                .rows(courses)
                .build();
    }

    @Override
    public void save(Course course) {
        if (ObjectUtils.isEmpty(course)) {
            throw new RuntimeException("参数错误");
        }
        boolean hasNull = BeanUtil.hasNullField(course, "id", "description", "createTime", "updateTime");
        if (hasNull) {
            throw new RuntimeException("参数错误");
        }
        course.setCreateTime(LocalDateTime.now());
        course.setUpdateTime(LocalDateTime.now());
        courseMapper.insert(course);
    }

    @Override
    public void delete(Integer id) {
        courseMapper.delete(id);
    }

    @Override
    public Course getById(Integer id) {
        return courseMapper.get(id);
    }

    @Override
    public void update(Course course) {
        course.setUpdateTime(LocalDateTime.now());
        courseMapper.update(course);
    }

    @Override
    public List<Course> list() {
        return courseMapper.selectList();
    }

    @Override
    public List<Course> listBySubject(String subject) {
        return courseMapper.selectBySubject(subject);
    }

}
